# coding: utf-8

import urllib.request

from docopt import docopt
import requests
import json
from prettytable import PrettyTable
from colorama import Fore

def cli():
    #arguments = docopt(__doc__, version='ticket 1.0')
    from_station = 'VAP'
    to_station = 'CUW'
    date = '2018-01-09'
    # 列表推导式，得到的是查询车次类型的集合
    #options = ''.join([key for key, value in arguments.items() if value is True])
    #print(options)

    url = ('https://kyfw.12306.cn/otn/leftTicket/queryZ?'
           'leftTicketDTO.train_date={}&'
           'leftTicketDTO.from_station={}&'
           'leftTicketDTO.to_station={}&'
           'purpose_codes=ADULT').format(date, from_station, to_station)

    print(url)

    request_data_body=urllib.request.urlopen(url).read().decode("utf-8")
    print(request_data_body)
    if(request_data_body==''):
        print(1)
    else:
        request_data_json = json.loads(request_data_body)
        print(request_data_json)
        print(type(request_data_json))
        raw_trains = request_data_json['data']['result']
        print(raw_trains)
        pt = PrettyTable()
        pt._set_field_names("车次　车站　时间　经历时　一等座　二等座　软卧　硬卧 硬座　无座".split())
        for raw_train in raw_trains:
            # split切割之后得到的是一个列表
            data_list = raw_train.split("|")
            train_no = data_list[3]
            initial = train_no[0].lower()
            # print(train_no[0])
            # 判断是否是查询特定车次的信息
            #if not options or initial in options:
            from_station_code = data_list[6]
            to_station_code = data_list[7]
            from_station_name = ''
            to_station_name = ''
            start_time = data_list[8]
            arrive_time = data_list[9]
            time_duration = data_list[10]
            first_class_seat = data_list[31] or "--"
            second_class_seat = data_list[30] or "--"
            soft_sleep = data_list[23] or "--"
            hard_sleep = data_list[28] or "--"
            hard_seat = data_list[29] or "--"
            no_seat = data_list[33] or "--"

            pt.add_row([
                # 对特定文字添加颜色
                train_no,
                '\n'.join([Fore.GREEN + from_station + Fore.RESET,
                           Fore.RED + to_station + Fore.RESET]),
                '\n'.join([Fore.GREEN + start_time + Fore.RESET, Fore.RED + arrive_time + Fore.RESET]),
                time_duration,
                first_class_seat,
                second_class_seat,
                soft_sleep,
                hard_sleep,
                hard_seat,
                no_seat
            ])

        print(pt)
cli()